/**
 * @Copyright: Interactive Business Solution Pte Ltd, Singapore
 * @Author: Li Wen, 2008-01-08
 * @Version: 080108.001
 * Data access object of tour item library object
 * 
 * TODO: other dao functions, such as insert, update, delete functions
 */
package com.ibsol.database
{
	import com.ibsol.model.TourItemLib;
	
	import flash.data.SQLConnection;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	public class TourItemLibDAO
	{
		private var _tourixDBConn:SQLConnection;
		/**
		 * TourItemLibDAO default constructor, gets tourix database connection
		 * @param:		null
		 */
		public function TourItemLibDAO()
		{
			_tourixDBConn = DBConnManager.getConnection("tourix");
		}
		/**
		 * Loads all tour item information for tour item library view
		 * @param:	resultHandler:Function			result function handler, return tour library item collection
		 * 			faultHandler:Function			fault function handler
		 */
		public function loadTourItems(resultHandler:Function, faultHandler:Function = null):void
		{
			var sqlStr:SQLStatement = new SQLStatement();
			sqlStr.sqlConnection = _tourixDBConn;
			sqlStr.text = "SELECT t.*, c.name as cityName, c.country FROM tourItemLib as t, city as c " + 
					"WHERE t.offlineOperator !='DEL' AND t.cityid = c.id";
			sqlStr.addEventListener(SQLEvent.RESULT,
				function (event:SQLEvent):void
				{
					resultHandler.call(this, typeArray(sqlStr.getResult().data));
				});
			sqlStr.addEventListener(SQLErrorEvent.ERROR, faultHandler == null ? sqlErrorHandler : faultHandler);
			sqlStr.execute();
		}
		/**
		 * Default SQL error handler, if above functions' fault handlers are null, this error handler is applied
		 * @param: event:SQLError	SQL Error event will be handled if there is an error
		 * @return: void
		 */
		private function sqlErrorHandler(event:SQLErrorEvent):void
		{
			mx.controls.Alert.show(event.text, "Error");
			trace(event.text);
		}
		/**
		 * Converts database object to TourItem class
		 * @param: o:Object database return object
		 * @return: TourItem object, after conversion
		 */
		private function typeObject(o:Object):TourItemLib
		{
			var t:TourItemLib = new TourItemLib();
			t.id = o.id;
			t.name = o.name;
			t.cityid = o.cityid;
			t.cityName = o.cityName;
			t.country = o.country;
			t.desp = o.desp;
			t.offlineOperator = o.offlineOperator;
			t.updateTime = o.updateTime;
			return t;
		}
		/**
		 * Converts array object to TourItem array collection
		 * @param: a:Array array of objects returned by SQL
		 * @return: ArrayCollection ArrayCollection of TourItem after conversion from Array
		 */
		private function typeArray(a:Array):ArrayCollection
		{
			if (a==null) return null;
			var ac:ArrayCollection = new ArrayCollection();
			for (var i:int; i<a.length; i++)
			{
				ac.addItem(typeObject(a[i]));
			}
			return ac;
		}

	}
}